<template>
  <!-- 全屏遮罩 -->
  <div v-if="visible" class="dialog-overlay" @click="close">
    <div class="dialog-wrapper" @click.stop>
      <div class="dialog-header">
        <h2 class="dialog-title">
          <span>问题详情</span>
          <em>{{ formData.title || '加载中...' }}</em>
        </h2>
        <button class="dialog-close-btn" @click="close">×</button>
      </div>

      <div class="dialog-body">
        <!-- 标题 -->
        <div class="form-group">
          <label class="form-label">标题</label>
          <p class="form-value">{{ formData.title }}</p>
        </div>

        <!-- 类型 -->
        <div class="form-group">
          <label class="form-label">类型</label>
          <span :class="['type-tag', getTypeTagClass(formData.type)]">
            {{ getTypeLabel(formData.type) }}
          </span>
        </div>

        <!-- 描述 -->
        <div class="form-group">
          <label class="form-label">问题描述</label>
          <MdPreview :modelValue="formData.description" />
        </div>

        <!-- 预期结果 -->
        <div class="form-group">
          <label class="form-label">预期结果</label>
          <MdPreview :modelValue="formData.expected" />
        </div>

        <!-- 附件上传 -->
        <div class="form-group">
          <label class="form-label">附件</label>
          <el-upload
              v-model:file-list="fileList"
              :auto-upload="false"
              :limit="10"
              accept=".txt,.log,.out,.java,.py,.c,.cpp,.js,.html,.htm,.css,.scss,.json,.xml,.yml,.yaml,.properties,.sql,.md,.markdown"
              multiple
              disabled
              class="custom-upload"
          >
            <button
                v-if="fileList.length > 0"
                type="button"
                class="btn btn-outline btn-sm"
                @click.stop="downloadAllAttachments(formData.id)"
                :disabled="downloading"
            >
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" viewBox="0 0 24 24" width="16" height="16">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
              </svg>
              下载所有附件 ({{ fileList.length }}个)
            </button>
            <span v-else class="no-attachment">无附件</span>
            <template #tip>
              <div class="upload-tip">
                支持 .md .txt .log 等格式，单个不超过 1MB。
              </div>
            </template>
          </el-upload>
        </div>

        <!-- 指定专家 -->
        <div class="form-group">
          <label class="form-label">指定专家</label>
          <div class="expert-tags">
            <span v-for="expert in pendingExperts" :key="expert.id" class="tag tag-info">
              {{ expert.username }}
            </span>
            <span v-if="pendingExperts.length === 0" class="text-muted">暂未指定专家</span>
          </div>
        </div>

        <!-- 评论区域 -->
        <div class="comment-section" v-if="questionStatus === 'in_progress' || questionStatus === 'resolved'">
          <template v-if="questionStatus === 'in_progress'">
            <h3 class="section-title">发表评论</h3>
            <MdEditor v-model="commentContent" :toolbars="customToolbars" @on-upload-img="handleUploadImage" placeholder="请输入您的评论..." />

            <div class="comment-actions">
              <button class="btn btn-primary btn-sm" @click="submitComment">发布评论</button>
            </div>
          </template>

          <!-- 评论列表 -->
          <div class="comments-list">
            <h3 class="section-title">全部评论 ({{ comments.length }})</h3>
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <div class="comment-header">
                <span class="comment-author">{{ comment.author }}</span>
                <span class="comment-time">{{ comment.time }}</span>
                <span class="comment-status" style="margin-left: 10px" v-if="questionStatus === 'in_progress' && currentUserId && comment.userId === currentUserId">
                  <template v-if="comment.status === 'pending'">待审核</template>
                  <template v-if="comment.status === 'approved'">审核通过</template>
                  <template v-if="comment.status === 'rejected'">已驳回</template>
                  <template v-if="comment.status === 'disabled'">已禁用</template>
                </span>

                <!-- 操作按钮：仅作者可见 -->
                <div class="comment-actions" v-if="questionStatus === 'in_progress' && currentUserId && comment.userId === currentUserId" style="margin-top: 0; margin-left: 10px">
                  <button class="btn btn-text btn-sm" @click="handleEditClick(comment)">编辑</button>
                  <button class="btn btn-text btn-sm text-red" @click="handleDeleteClick(comment)">删除</button>
                </div>
              </div>
              <MdPreview :modelValue="comment.content" />
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作区 -->
      <div class="dialog-footer">
        <button class="btn btn-primary" @click="close">关闭</button>
      </div>
    </div>
  </div>

  <!-- 注册组件 -->
  <CommentEditDialog
      ref="editDialogRef"
      :comment-id="editingComment.id"
      @save="handleSaveEdit"
  />
</template>

<script setup>
import {ref, defineExpose, onMounted, onBeforeMount} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '@/utils/request'
import { MdPreview, MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';
import CommentEditDialog from '@/components/CommentEditDialog.vue'
import "viewerjs/dist/viewer.css";
import { bindImgClick } from "@/utils/util.js";

// 弹窗是否可见
const visible = ref(false)

// 数据模型
const formData = ref({})
const fileList = ref([])
const pendingExperts = ref([]) // 存储待响应的专家
const downloading = ref(false)

// 类型映射
const typeMap = {}

async function loadTags() {
  const res = await request.get(`/api/tag/listAll`)
  if (res.data) {
    for (let i = 0; i < res.data.length; i++) {
      typeMap[res.data[i].id + ""] = res.data[i].name
    }
  }
}

const getTypeLabel = (val) => typeMap[val] || '其他'
const getTypeTagClass = (val) => ({
  "1": 'tag-green',
  "2": 'tag-blue',
  "3": 'tag-yellow',
  "4": 'tag-red',
  "5": 'tag-purple',
  "6": 'tag-orange',
})[val] || 'tag-gray'

const questionStatus = ref(null);
const questionId = ref(null);

// 打开弹窗并拉取数据
const open = async (row) => {
  try {
    questionStatus.value = row.status;
    questionId.value = row.id;
    const res = await request.get(`/api/questions/${row.id}`)
    const data = res.data

    formData.value = {
      id: data.id,
      title: data.title,
      type: data.type,
      description: data.description,
      expected: data.expected,
    }

    // 处理附件
    fileList.value = data.attachments || []

    // 处理专家
    pendingExperts.value = data.pendingExperts || []

    await loadTags();
    // if (questionStatus.value === 'in_progress') {
      // 加载评论
      await loadComments()
    // }

    visible.value = true
  } catch (err) {
    // ElMessage.error('获取问题详情失败')
    console.error(err)
  }
}

// 关闭弹窗
const close = () => {
  visible.value = false
}

// 下载所有附件打包 ZIP
const downloadAllAttachments = async (questionId) => {
  if (!questionId) return

  downloading.value = true
  try {
    const response = await request({
      url: `/api/attachment/download/${questionId}`,
      skipCodeCheck: true,
      method: 'get',
      responseType: 'blob'
    })

    const blob = response.data
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `attachments_${questionId}.zip`
    link.click()
    URL.revokeObjectURL(link.href)

    ElMessage.success('附件下载完成')
  } catch (error) {
    // if (error.response?.status === 404) {
    //   ElMessage.warning('该问题暂无附件可下载')
    // } else {
    //   ElMessage.error('下载失败，请稍后再试')
    // }
  } finally {
    downloading.value = false
  }
}

// 暴露方法给父组件调用
defineExpose({ open })

// 定义你想要保留的工具栏按钮
const customToolbars = [
  'bold',      // 加粗
  'italic',    // 斜体
  '|',         // 分隔线
  'ul',        // 无序列表
  'ol',        // 有序列表
  '|',
  'code',      // 行内代码
  'code-block', // 代码块
  '|',
  'link',      // 链接
  'image',     // 图片（可去掉）
  '|',
  'revoke',    // 撤销
  'next'       // 重做
];

const handleUploadImage = async (files, callback) => {
  const formData = new FormData()
  formData.append('file', files[0])

  try {
    const res = await request.post('/api/attachment/upload-image', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    callback([res.data]) // 回调传入图片 URL 数组
  } catch (err) {
    ElMessage.error('图片上传失败')
    callback([]) // 失败也要调用，避免卡住
  }
}

// 评论内容
const commentContent = ref('')

// 真实评论列表（替换原来的模拟数据）
const comments = ref([])

// 获取已通过的评论列表
const loadComments = async () => {
  try {
    const res = await request.get(`/api/comments/question/${questionId.value}`)
    if (res.data && Array.isArray(res.data)) {
      comments.value = res.data.map(c => ({
        id: c.id,
        questionId: c.questionId,
        userId: c.userId,
        author: c.username || '未知用户',
        time: formatTime(c.createdAt),
        content: c.content,
        status: c.status,
      }))
    } else {
      comments.value = []
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.warning('无法加载评论')
    comments.value = []
  }
}

// 时间格式化函数（ISO 时间转 YYYY-MM-DD HH:mm）
const formatTime = (isoString) => {
  if (!isoString) return ''
  const d = new Date(isoString)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

// 提交真实评论
const submitComment = async () => {
  const content = commentContent.value.trim()
  if (!content) {
    ElMessage.warning('评论内容不能为空')
    return
  }

  try {
    await request.post('/api/comments', {
      questionId: formData.value.id,
      content
    })

    // 提交成功后刷新评论列表
    commentContent.value = ''
    ElMessage.success('评论已提交，等待审核')
    // 加载评论
    await loadComments()
  } catch (error) {
    console.error('发表评论失败:', error)
    // ElMessage.error('提交失败，请稍后再试')
  }
}

// ========== 新增变量 ==========
const editDialogRef = ref()     // 引用弹窗实例
const editingComment = ref({
  content: "",
  id: "",
})   // 当前正在编辑的评论对象

// ========== JWT 工具函数：解析 token 获取 userId ==========
const getUserIdFromToken = () => {
  const token = localStorage.getItem('token')
  if (!token) return null
  try {
    const payload = parseJwt(token)
    return payload.userId // 根据你的 JWT payload 字段名调整
  } catch (e) {
    console.error('解析 JWT 失败', e)
    return null
  }
}

/**
 * 安全解析 JWT token（支持中文、Base64URL）
 */
function parseJwt(token) {
  if (!token) return null;

  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;

    let payload = parts[1];
    payload = payload.replace(/-/g, '+').replace(/_/g, '/');
    while (payload.length % 4) payload += '=';

    const decoded = decodeURIComponent(
        atob(payload)
            .split('')
            .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
            .join('')
    );

    return JSON.parse(decoded);
  } catch (e) {
    console.error('JWT 解析失败:', e);
    return null;
  }
}

// 当前用户 ID
const currentUserId = ref(null)

// 页面加载时获取用户 ID
request.interceptors.request.use(config => {
  if (!currentUserId.value) {
    currentUserId.value = getUserIdFromToken()
  }
  return config
})
// 或者直接初始化一次
currentUserId.value = getUserIdFromToken()

// ========== 编辑评论 ==========
const handleEditClick = (comment) => {
  if (!currentUserId.value) {
    ElMessage.warning('请先登录')
    return
  }
  if (comment.userId !== currentUserId.value) {
    ElMessage.error('无法编辑他人评论')
    return
  }

  editingComment.value = comment
  editDialogRef.value?.open(editingComment.value.content)
}

// 保存编辑后的评论
const handleSaveEdit = (newContent) => {
  // 更新本地评论列表
  const index = comments.value.findIndex(c => c.id === editingComment.value.id)
  if (index !== -1) {
    comments.value[index].content = newContent
    comments.value[index].time = formatTime(new Date().toISOString()) // 可选：更新时间为当前
  }
  // ElMessage.success('评论已更新')
  // 加载评论
  loadComments()
}

// ========== 删除评论 ==========
const handleDeleteClick = async (comment) => {
  if (!currentUserId.value) {
    ElMessage.warning('请先登录')
    return
  }
  if (comment.userId !== currentUserId.value) {
    ElMessage.error('无法删除他人评论')
    return
  }

  try {
    await ElMessageBox.confirm(
        '确定要删除这条评论吗？删除后不可恢复。',
        '警告',
        { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
    )

    await request.delete(`/api/comments/${comment.id}`)
    // 从列表移除
    comments.value = comments.value.filter(c => c.id !== comment.id)
    ElMessage.success('评论已删除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请稍后再试')
    }
  }
}

let interval;

onMounted(() => {
  interval = setInterval(function () {
    bindImgClick();
  }, 1000);
});

onBeforeMount(() => {
  if (interval) {{
    clearInterval(interval);
  }}
});
</script>

<style scoped>
/* 遮罩层 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

/* 对话框主体 */
.dialog-wrapper {
  background: var(--white);
  box-shadow: var(--shadow);
  width: 100vw;
  height: 100vh;
  border: 1px solid var(--border);
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

/* 头部 */
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  border-bottom: 1px solid var(--border);
}

.dialog-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text);
}

.dialog-title em {
  display: block;
  font-size: 16px;
  font-weight: normal;
  font-style: normal;
  color: var(--text-light);
  margin-top: 4px;
}

.dialog-close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: var(--text-muted);
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.dialog-close-btn:hover {
  background: #f1f5f9;
  color: var(--text);
}

/* 主体内容 */
.dialog-body {
  padding: 32px;
  flex: 1;
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 20px;
  color: var(--text);
  font-weight: 500;
}

.form-value {
  padding: 12px 16px;
  background: #f8fafc;
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: var(--text);
  margin: 0;
}

.pre-line {
  white-space: pre-line;
}

.no-attachment {
  color: var(--text-muted);
  font-style: italic;
}

/* 上传组件美化 */
.custom-upload ::v-deep .el-upload-list {
  margin-top: 12px;
}

.upload-tip {
  font-size: 13px;
  color: var(--text-muted);
  margin-top: 8px;
}

/* 标签样式复用 */
.type-tag,
.tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.tag-info { background: #e0f2fe; color: #0369a1; }

/* 类型标签颜色 */
.tag-blue { background: #eff6ff; color: #1d4ed8; }
.tag-green { background: #ecfdf5; color: #059669; }
.tag-yellow { background: #fffbeb; color: #d97706; }
.tag-red { background: #fee2e2; color: #dc2626; }
.tag-purple { background: #f3e8ff; color: #7c3aed; }
.tag-orange { background: #fff7ed; color: #c2410c; }
.tag-gray { background: #f1f5f9; color: #64748b; }

/* 指定专家 */
.expert-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  min-height: 36px;
  padding: 8px 0;
}

.text-muted {
  color: var(--text-muted);
  font-size: 14px;
}

/* 底部按钮 */
.dialog-footer {
  padding: 20px 32px;
  text-align: right;
  border-top: 1px solid var(--border);
  background: #fbfdff;
  border-radius: 0 0 12px 12px;
}

.btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
}

.btn-primary {
  background: var(--primary);
  color: white;
}

.btn-primary:hover {
  background: var(--primary-hover);
}

.btn-outline {
  background: transparent;
  color: var(--primary);
  border: 1px solid var(--primary);
}

.btn-outline:hover {
  background: #ebf5ff;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 13px;
}

/* 响应式 */
@media (max-width: 768px) {
  .dialog-wrapper {
    margin: 20px;
    border-radius: 12px;
  }

  .dialog-header,
  .dialog-body,
  .dialog-footer {
    padding: 20px;
  }

  .dialog-title {
    font-size: 18px;
  }

  .dialog-title em {
    font-size: 14px;
  }
}

.dialog-wrapper::-webkit-scrollbar {
  width: 0.5rem;
}

.dialog-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 0.5rem;
}

.dialog-wrapper::-webkit-scrollbar-thumb {
  background: #3498db;
  border-radius: 0.5rem;
}

.dialog-wrapper::-webkit-scrollbar-thumb:hover {
  background: #2980b9;
}

/* 评论区域 */
.comment-section {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 2px dashed var(--border);
}

.section-title {
  font-size: 18px;
  color: var(--text);
  font-weight: 600;
  margin-bottom: 16px;
}

/* Markdown 编辑器样式覆盖 */
.comment-section .md-editor {
  border: 1px solid var(--border);
  border-radius: 8px;
  overflow: hidden;
  background-color: #f8fafc;
}

.comment-section .md-editor :deep(.editor-wrapper) {
  min-height: 120px;
}

.comment-section .md-editor :deep(textarea) {
  font-size: 14px !important;
  line-height: 1.6 !important;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 评论列表 */
.comments-list .comment-item {
  background: #f8fafc;
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.comments-list .comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: var(--text-light);
}

.comments-list .comment-author {
  font-weight: 500;
  color: var(--text);
  flex: 1;
}

.comments-list .comment-time {
  color: var(--text-muted);
}

.comments-list .comment-status {
  color: #f56c6c;
}

/* Markdown 预览样式 */
.comments-list .md-editor-preview {
  font-size: 14px;
  color: var(--text);
  line-height: 1.6;
}

.comments-list .md-editor-preview p,
.comments-list .md-editor-preview ul,
.comments-list .md-editor-preview ol {
  margin: 8px 0;
}

.comments-list .md-editor-preview pre {
  background: #f1f5f9;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  font-size: 13px;
}

/* 文字按钮 */
.btn-text {
  background: transparent;
  color: #409eff;
  padding: 0 8px;
  font-size: 13px;
  border: none;
}

.btn-text:hover {
  background: #ecf5ff;
  color: #337ecc;
}

.text-red {
  color: #f56c6c !important;
}

.text-red:hover {
  background: #fef0f0 !important;
  color: #e65151 !important;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  color: var(--text-light);
}
</style>
